<!--
 * @Author: 41
 * @Date: 2022-02-18 17:31:34
 * @LastEditors: YWY
 * @LastEditTime: 2022-03-08 11:27:22
 * @Description: 
-->
<template>
  <div class="bg">
    <header class="close" @click="close">关闭</header>
    <h1 class="title">CampusSNS</h1>
    <van-form>
      <van-cell-group inset class="name-box login-message">
        <van-field
          v-model="form_data.username"
          :label="isLogin ? '登录账号' : '注册账号'"
          :placeholder="isLogin ? '登录账号' : '注册账号'"
          :rules="[
            {
              required: true,
              message: isLogin ? '请填写账号' : '请填写账号',
            },
          ]"
        />
        <!-- <van-field
          v-model="form_data.code"
          center
          clearable
          label="短信验证码"
          placeholder="请输入短信验证码"
          v-show="!isLogin"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              v-if="!phone_data.flag"
              @click="getCheck"
              >发送验证码</van-button
            >
            <span v-else>{{ phone_data.remainTime }}s</span>
          </template>
        </van-field> -->
      </van-cell-group>
      <van-cell-group inset class="password-box login-message">
        <van-field
          v-model="form_data.password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
          autocomplete="on"
          v-show="!canSee"
        >
          <template #button>
            <span
              class="iconfont cansee-icon icon-xianshikejian"
              @click="canSee = !canSee"
            ></span>
          </template>
        </van-field>
        <van-field
          v-model="form_data.password"
          type="primary"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
          autocomplete="on"
          v-show="canSee"
        >
          <template #button>
            <span
              class="iconfont cansee-icon icon-yincangbukejian"
              @click="canSee = !canSee"
            ></span>
          </template>
        </van-field>
      </van-cell-group>
      <div style="margin: 30px auto 25px auto; width: 335px">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          @click="onSubmit"
        >
          {{ buttonMessage1 }}
        </van-button>
      </div>
      <div style="margin: 0px auto 30px auto; width: 335px">
        <van-button
          round
          block
          type="primary"
          color="#72cf4d"
          @click="change"
          plain
        >
          {{ buttonMessage2 }}
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
//分两个模块，一个登陆注册一个找回密码
//功能1：登录注册要可以来回切换
//功能2：注册的获取验证码的计数器
import { Toast } from "vant";
import { useRouter } from "vue-router";
import { onBeforeMount, reactive, ref } from "vue";
import { login } from "@/api/services/user.service";
import { register } from "../api/services/user.service";
import { mainStore } from "@/store/index.js";
import { userStore } from "@/store/userdata.js";
import { wsConnection } from "../utils/ws/wsUtils";
// import { mainStore } from "../store/index";
const loginOrRegister = function (isLogin, buttonMessage1, buttonMessage2) {
  return function change(isFirst) {
    if (isFirst != 1) {
      isLogin.value = !isLogin.value;
    }
    if (isLogin.value) {
      buttonMessage1.value = "登录";
      buttonMessage2.value = "没有账号，立即注册";
    } else {
      buttonMessage1.value = "注册";
      buttonMessage2.value = "已有账号，前往登录";
    }
  };
};
export default {
  name: "Login",
  setup() {
    const main = mainStore();
    const user = userStore();
    const form_data = reactive({
      username: "",
      password: "",
      ppassword: "",
      code: "",
    });
    const phone_data = reactive({
      remainTime: 60,
      timer: null,
      flag: false,
    });
    const router = useRouter();
    let buttonMessage1 = ref(""),
      buttonMessage2 = ref("");
    let isLogin = ref(1);
    let canSee = ref();
    let canSeeMessage = ref("");
    canSeeMessage = "password";
    canSee.value = false;
    const change = loginOrRegister(isLogin, buttonMessage1, buttonMessage2);
    const onSubmit = async function () {
      if (!checkMessage()) return;
      if (isLogin.value) {
        login(form_data.username, form_data.password)
          .then((res) => {
            console.log(res);
            if (res.message == "用户登录成功") {
              localStorage.removeItem("Authorization");
              localStorage.setItem("Authorization", res.result.token);
              console.log(res);
              close();
              Toast.success("登录成功");
              main.logIn();
              user.logIn(res.result.user);
              console.log(user.id);
              wsConnection(res.result.token);
            }
          })
          .catch((rej) => {
            console.log(rej);
            Toast.fail("用户名或密码错误");
          });
      } else {
        try {
          let res = await register(
            form_data.username,
            form_data.password,
            "保密",
            true
          );
          if (res.message == "用户注册成功") {
            Toast.success("注册成功");
            login(form_data.username, form_data.password).then((res) => {
              localStorage.removeItem("Authorization");
              localStorage.setItem("Authorization", res.result.token);
              console.log(res);
              close();
              main.logIn();
              user.logIn(res.result.user);
              console.log(user.id);
              wsConnection(res.result.token);
            });
          }
        } catch {
          Toast.fail("用户名已存在");
        }
      }
    };
    const setStore = function () {};
    const checkMessage = function () {
      if (form_data.username.length < 5 || form_data.username.length > 16) {
        Toast.fail("用户名在5到16个字符之间");
        return false;
      }
      // if (
      //   !isLogin.value &&
      //   (form_data.username.length != 11 || isNaN(parseInt(form_data.username)))
      // ) {
      //   Toast.fail("请输入正确的手机号");
      //   return false;
      // }
      if (form_data.password.length < 6 || form_data.password.length > 18) {
        Toast.fail("密码在6到18个字符之间");
        return false;
      }
      // if (!isLogin.value && form_data.code.length != 6) {
      //   Toast.fail("需要6位数验证码");
      //   return false;
      // }
      return true;
    };
    const close = function () {
      router.push("/");
    };
    const countDown = function () {
      phone_data.flag = true;
      phone_data.timer = setInterval(() => {
        phone_data.remainTime--;
        if (phone_data.remainTime <= 0) {
          phone_data.flag = false;
          phone_data.remainTime = 60;
          clearInterval(phone_data.timer);
        }
      }, 1000);
    };
    const getCheck = function () {
      if (
        !isLogin.value &&
        (form_data.username.length != 11 || isNaN(parseInt(form_data.username)))
      ) {
        Toast.fail("请输入正确的手机号");
        return false;
      }
      countDown();
      Toast.success("已发送验证码");
    };
    const checkSee = function () {
      canSee.value = !canSee.value;
    };
    onBeforeMount(() => {
      change(1);
    });
    return {
      buttonMessage1,
      buttonMessage2,
      isLogin,
      canSee,
      canSeeMessage,
      form_data,
      phone_data,
      close,
      onSubmit,
      change,
      getCheck,
      checkSee,
    };
  },
};
</script>

<style scoped>
.cansee-icon {
  font-size: 18px;
}
.close {
  font-size: 14px;
  padding: 7px;
  color: #969799;
  text-align: left;
}
.title {
  width: 185px;
  margin: 50px auto;
  font-weight: 400;
}
.name-box {
  margin: 20px;
}
.password-box {
  margin: 20px;
}
.login-message {
  border-radius: 17px;
  border: 2px solid #e2e1e1;
}
/* 覆盖vant样式 */
.login-message .van-field__label {
  width: 50px !important;
  margin-right: 8px !important;
}
</style>
